<script lang="ts" setup>
import type { TechniciansApi } from '#/api/spa/technicians';
import type { VxeTableInstance } from '#/adapter/vxe-table';

import { Page, useVbenModal } from '@vben/common-ui';
import { cloneDeep, formatDateTime } from '@vben/utils';
import {
  Button,
  message,
  Tabs,
  Pagination,
  Form,
  RangePicker,
  DatePicker,
  Select,
  Input,
} from 'ant-design-vue';
import { DictTag } from '#/components/dict-tag';
import TechniciansForm from './modules/form.vue';
import { Download, Plus, RefreshCw, Search, Trash2 } from '@vben/icons';
import { ContentWrap } from '#/components/content-wrap';
import { VxeColumn, VxeTable } from '#/adapter/vxe-table';
import { TableToolbar } from '#/components/table-toolbar';
import { useTableToolbar } from '#/hooks';

import { ref, h, reactive, onMounted, nextTick } from 'vue';
import { $t } from '#/locales';
import { isEmpty } from '@vben/utils';
import {
  getTechniciansPage,
  deleteTechnicians,
  deleteTechniciansList,
  exportTechnicians,
} from '#/api/spa/technicians';
import { downloadFileFromBlobPart } from '@vben/utils';

import { getRangePickerDefaultProps } from '#/utils';
const loading = ref(true); // 列表的加载中
const list = ref<TechniciansApi.Technicians[]>([]); // 列表的数据

const total = ref(0); // 列表的总页数
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  technicianCode: undefined,
  name: undefined,
  gender: undefined,
  department: undefined,
  employeeCard: undefined,
  productType: undefined,
  status: undefined,
  currentServiceTime: undefined,
  currentServiceName: undefined,
  currentRoomNumber: undefined,
  currentCount: undefined,
  totalCount: undefined,
  createTime: undefined,
});
const queryFormRef = ref(); // 搜索的表单
const exportLoading = ref(false); // 导出的加载中

/** 查询列表 */
const getList = async () => {
  loading.value = true;
  try {
    const params = cloneDeep(queryParams) as any;
    if (params.currentServiceTime && Array.isArray(params.currentServiceTime)) {
      params.currentServiceTime = (params.currentServiceTime as string[]).join(
        ',',
      );
    }
    if (params.createTime && Array.isArray(params.createTime)) {
      params.createTime = (params.createTime as string[]).join(',');
    }
    const data = await getTechniciansPage(params);
    list.value = data.list;
    total.value = data.total;
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: TechniciansForm,
  destroyOnClose: true,
});

/** 创建技师管理 */
function handleCreate() {
  formModalApi.setData({}).open();
}

/** 编辑技师管理 */
function handleEdit(row: TechniciansApi.Technicians) {
  formModalApi.setData(row).open();
}

/** 删除技师管理 */
async function handleDelete(row: TechniciansApi.Technicians) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteTechnicians(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
      key: 'action_process_msg',
    });
    await getList();
  } finally {
    hideLoading();
  }
}

/** 批量删除技师管理 */
async function handleDeleteBatch() {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting'),
    duration: 0,
    key: 'action_process_msg',
  });
  try {
    await deleteTechniciansList(checkedIds.value);
    checkedIds.value = [];
    message.success($t('ui.actionMessage.deleteSuccess'));
    await getList();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: TechniciansApi.Technicians[];
}) {
  checkedIds.value = records.map((item) => item.id);
}

/** 导出表格 */
async function onExport() {
  try {
    exportLoading.value = true;
    const data = await exportTechnicians(queryParams);
    downloadFileFromBlobPart({ fileName: '技师管理.xls', source: data });
  } finally {
    exportLoading.value = false;
  }
}

/** 初始化 */
const { hiddenSearchBar, tableToolbarRef, tableRef } = useTableToolbar();
onMounted(() => {
  getList();
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="getList" />

    <ContentWrap v-if="!hiddenSearchBar">
      <!-- 搜索工作栏 -->
      <Form :model="queryParams" ref="queryFormRef" layout="inline">
        <Form.Item label="技师编号" name="technicianCode">
          <Input
            v-model:value="queryParams.technicianCode"
            placeholder="请输入技师编号"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="技师姓名" name="name">
          <Input
            v-model:value="queryParams.name"
            placeholder="请输入技师姓名"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="性别" name="gender">
          <Input
            v-model:value="queryParams.gender"
            placeholder="请输入性别"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="所属部门" name="department">
          <Input
            v-model:value="queryParams.department"
            placeholder="请输入所属部门"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="员工卡号" name="employeeCard">
          <Input
            v-model:value="queryParams.employeeCard"
            placeholder="请输入员工卡号"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="产品类型" name="productType">
          <Select
            v-model:value="queryParams.productType"
            placeholder="请选择产品类型"
            allowClear
            class="w-full"
          >
            <Select.Option label="请选择字典生成" value="" />
          </Select>
        </Form.Item>
        <Form.Item label="技师状态" name="status">
          <Select
            v-model:value="queryParams.status"
            placeholder="请选择技师状态"
            allowClear
            class="w-full"
          >
            <Select.Option label="请选择字典生成" value="" />
          </Select>
        </Form.Item>
        <Form.Item label="当前服务时长" name="currentServiceTime">
          <RangePicker
            v-model:value="queryParams.currentServiceTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="当前服务项目" name="currentServiceName">
          <Input
            v-model:value="queryParams.currentServiceName"
            placeholder="请输入当前服务项目"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="当前房间号" name="currentRoomNumber">
          <Input
            v-model:value="queryParams.currentRoomNumber"
            placeholder="请输入当前房间号"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="当前服务次数" name="currentCount">
          <Input
            v-model:value="queryParams.currentCount"
            placeholder="请输入当前服务次数"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="总服务次数" name="totalCount">
          <Input
            v-model:value="queryParams.totalCount"
            placeholder="请输入总服务次数"
            allowClear
            @pressEnter="handleQuery"
            class="w-full"
          />
        </Form.Item>
        <Form.Item label="创建时间" name="createTime">
          <RangePicker
            v-model:value="queryParams.createTime"
            v-bind="getRangePickerDefaultProps()"
            class="w-full"
          />
        </Form.Item>
        <Form.Item>
          <Button class="ml-2" @click="resetQuery"> 重置 </Button>
          <Button class="ml-2" @click="handleQuery" type="primary">
            搜索
          </Button>
        </Form.Item>
      </Form>
    </ContentWrap>

    <!-- 列表 -->
    <ContentWrap title="技师管理">
      <template #extra>
        <TableToolbar
          ref="tableToolbarRef"
          v-model:hidden-search="hiddenSearchBar"
        >
          <Button
            class="ml-2"
            :icon="h(Plus)"
            type="primary"
            @click="handleCreate"
            v-access:code="['spa:technicians:create']"
          >
            {{ $t('ui.actionTitle.create', ['技师管理']) }}
          </Button>
          <Button
            :icon="h(Download)"
            type="primary"
            class="ml-2"
            :loading="exportLoading"
            @click="onExport"
            v-access:code="['spa:technicians:export']"
          >
            {{ $t('ui.actionTitle.export') }}
          </Button>
          <Button
            :icon="h(Trash2)"
            type="primary"
            danger
            class="ml-2"
            :disabled="isEmpty(checkedIds)"
            @click="handleDeleteBatch"
            v-access:code="['spa:technicians:delete']"
          >
            批量删除
          </Button>
        </TableToolbar>
      </template>
      <vxe-table
        ref="tableRef"
        :data="list"
        show-overflow
        :loading="loading"
        @checkboxAll="handleRowCheckboxChange"
        @checkboxChange="handleRowCheckboxChange"
      >
        <vxe-column type="checkbox" width="40"></vxe-column>
        <vxe-column field="id" title="主键ID" align="center" />
        <vxe-column field="technicianCode" title="技师编号" align="center" />
        <vxe-column field="name" title="技师姓名" align="center" />
        <vxe-column field="gender" title="性别" align="center" />
        <vxe-column field="department" title="所属部门" align="center" />
        <vxe-column field="employeeCard" title="员工卡号" align="center" />
        <vxe-column field="productType" title="产品类型" align="center" />
        <vxe-column field="status" title="技师状态" align="center" />
        <vxe-column
          field="currentServiceTime"
          title="当前服务时长"
          align="center"
        />
        <vxe-column
          field="currentServiceName"
          title="当前服务项目"
          align="center"
        />
        <vxe-column
          field="currentRoomNumber"
          title="当前房间号"
          align="center"
        />
        <vxe-column field="currentCount" title="当前服务次数" align="center" />
        <vxe-column field="totalCount" title="总服务次数" align="center" />
        <vxe-column field="createTime" title="创建时间" align="center">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </vxe-column>
        <vxe-column field="operation" title="操作" align="center">
          <template #default="{ row }">
            <Button
              size="small"
              type="link"
              @click="handleEdit(row as any)"
              v-access:code="['spa:technicians:update']"
            >
              {{ $t('ui.actionTitle.edit') }}
            </Button>
            <Button
              size="small"
              type="link"
              danger
              class="ml-2"
              @click="handleDelete(row as any)"
              v-access:code="['spa:technicians:delete']"
            >
              {{ $t('ui.actionTitle.delete') }}
            </Button>
          </template>
        </vxe-column>
      </vxe-table>
      <!-- 分页 -->
      <div class="mt-2 flex justify-end">
        <Pagination
          :total="total"
          v-model:current="queryParams.pageNo"
          v-model:page-size="queryParams.pageSize"
          show-size-changer
          @change="getList"
        />
      </div>
    </ContentWrap>
  </Page>
</template>
